from django.core.paginator import Paginator
from django.db.models import F
from django.shortcuts import render, get_object_or_404

# Create your views here.
from system.models import News
from utils import contants
from utils.verify import VerifyCode


def news_list(request, template_name='news_list.html'):
    '''新闻列表'''

    # 分页
    page = request.GET.get('page', 1)
    page_size = 20

    news = News.objects.filter(types=contants.NEWS_TYPE_NEW, is_valid=True)
    # 获取分页器对象
    p = Paginator(news, page_size)
    # 调用方法获取数据
    page_data = p.page(page)
    return render(request, template_name, {
        'page_data': page_data,

    })

def news_detail(request, pk, template_name='news_info.html'):
    # 新闻详情
    new_obj = get_object_or_404(News, pk=pk, is_valid=True)
    # 每查看一次页面 浏览次数+1
    new_obj.view_count = F('view_count') + 1
    new_obj.save()
    new_obj.refresh_from_db()
    return render(request, template_name, {
        'new_obj': new_obj,
    } )


def verify_code(request):
    '''验证码的显示'''
    client = VerifyCode(request)
    return client.gen_code()